package com.wushi.lenovo.asia5b.app_ui.h5;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.luck.picture.lib.permissions.RxPermissions;
import com.mvp.utils.ToastUtil;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_model.h5.H5Bean;
import com.wushi.lenovo.asia5b.app_ui.home.activity.SearchActivity;
import com.wushi.lenovo.asia5b.app_ui.home.activity.SnapActivity;
import com.wushi.lenovo.asia5b.app_utils.eye.EyeUtils;
import com.wushi.lenovo.asia5b.app_utils.helper.H5Hepler;

import java.net.URLDecoder;
import java.util.LinkedHashSet;

import butterknife.BindView;
import butterknife.OnClick;

import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2019/4/10.
 */
public class SearchViewActivity extends H5Activity {
    @BindView(R.id.et_search_content)
    TextView et_search_content;
    @BindView(R.id.iv_search_icon)
    ImageView iv_search_icon;
    @BindView(R.id.pb_category)
    ContentLoadingProgressBar progress;
    @BindView(R.id.ll_category_vessel)
    LinearLayout ll_vessel;
    protected WebView webView;

    public static void startSearchViewActivityByKeyword(Context context, String keyword) {
        d("--->>>>>>>>---startSearchViewActivityByKeyword");
        Intent intent = new Intent(context, SearchViewActivity.class);
        intent.putExtra("keyword", keyword);
        context.startActivity(intent);
    }

    public static void startSearchViewActivityByImgpath(Context context, String imgpath) {
        d("--->>>>>>>>---startSearchViewActivityByImgpath");
        Intent intent = new Intent(context, SearchViewActivity.class);
        intent.putExtra(CommonConstant.SNAP_PREVIEW_PATH, imgpath);
        context.startActivity(intent);
    }


    @Override
    protected WebView getWebView() {
        return webView;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_searchview;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            setIntent(intent);
            getIntentData();
        }

    }

    private void getIntentData() {
        String keyword = getIntent().getStringExtra("keyword");
        String imgpath = getIntent().getStringExtra(CommonConstant.SNAP_PREVIEW_PATH);
        d("--->>>>>>>>---keyword:" + keyword);
        d("--->>>>>>>>---imgpath:" + imgpath);
        setUrlByKeyword(keyword);
        searchProductBySnap(imgpath);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initEvent();
        initData();
        getIntentData();
    }

    private final LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();

    private void searchProductBySnap(String imgpath) {
        if (!TextUtils.isEmpty(imgpath)) {
            getPresenter().searchProductBySnap(this,imgpath);
        }
    }

    public void setUrlByKeyword(String keyword) {
        if (!TextUtils.isEmpty(keyword)) {
            String url = H5Hepler.getH5_Url(String.format("/searchInfo?keyword=%s", keyword));
            webView.loadUrl(url);

            d("--->>>>>>>>---url:" + url);

            //保存搜索关键词
            et_search_content.setText(keyword);
        }
    }

    @Override
    protected void initView() {
        //使用new方式这是为了解决当(settings.setJavaScriptEnabled(true))之后会出现TextToSpeech的内存泄漏
        webView = new WebView(this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        webView.setLayoutParams(layoutParams);
        ll_vessel.addView(webView);
        setting(webView);
        setWebViewChormeClient(webView, progress);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void callBackByJs(H5Bean h5Bean) {
        super.callBackByJs(h5Bean);
        if (h5Bean != null) {
        }
    }

    @Override
    protected void initEvent() {
        webView.addJavascriptInterface(jsCall, H5_JSCALL_NAME);
    }

    @Override
    protected void loadUrl(String url) {
        super.loadUrl(url);
        //      https:asia.wusfamily.cn/searchInfo?keyword=%E8%A1%AC%E8%A1%AB&asiaH5=1&lang=en

        try {
            if (!TextUtils.isEmpty(url)) {
                Uri uri = Uri.parse(url);
                String keyword = uri.getQueryParameter("keyword");
                if (!TextUtils.isEmpty(keyword)) {
                    keyword = keyword.toLowerCase();
                    keyword = URLDecoder.decode(keyword, "utf-8");
                    if (!TextUtils.isEmpty(keyword) && linkedHashSet.contains(keyword)) {
                        et_search_content.setText(keyword);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({
            R.id.iv_search_camera,
            R.id.ll_search_iconvessel
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_search_iconvessel:
                startActivity(new Intent(mActivity, SearchActivity.class));
                break;
            case R.id.iv_search_camera:
                EyeUtils.tagPermission();
                new RxPermissions(mActivity)
                        .request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(aBoolean -> {
                            if (aBoolean) {
                                startActivity(new Intent(mActivity, SnapActivity.class));
                            } else {
                                ToastUtil.showToast(getString(R.string.permission_error1));
                            }
                        });
                break;
        }
    }

    @Override
    public void searchProductBySnapResult(String s) {
        if (!TextUtils.isEmpty(s)) {
            try {
                s = URLDecoder.decode(s, "UTF-8");
                if (!TextUtils.isEmpty(s)) {
                    String url = H5Hepler.getH5_Url(String.format("/searchInfo?secure_url=%s", s));
//                    et_search_content.setText("");
                    webView.loadUrl(url);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
